<template lang="pug">
data-page(
  v-bind="pageParams"
  style="padding: 0;"
)
  mt-table(
    v-bind="tableProps"
  )

  edit-form(
    v-bind="editFormProps"
  )
collectionMethod(v-model="collectionMethodShow" :selectionRow= "selectionRow" @message-to-parent="request('tableData')")
</template>

<script setup lang="ts">
import {
  type FormItemProps,
  type IAction,
  type DataPageProps,
  type Action,
  type EditFormProps,
  type TableProps,
  useNotify,
} from "@scmt/common-components";
import { type QueryPagination, useApi } from "@scmt/core-api";
import type { CombinedEntity, combinedParams } from "@scmt/api-lis-combined";
import collectionMethod from "./collectionMethod.vue";
import { useRequest } from "@scmt/common-hooks";

const $api = useApi();
const $notify = useNotify();
const queryPramas = reactive<combinedParams>({
  pageNum: 1,
  pageSize: 20,
});
const editingObj = ref<CombinedEntity>(null);
const selectEquipment = defineModel();
const selectionRow = ref([]);
const collectionMethodShow = ref(false);

const { request, data, loadingMap } = useRequest({
  tableData: (q: any) => {
    const params = Object.assign({}, queryPramas, q);
    return $api.lis.combined.query(params);
  },
  save: (model: CombinedEntity) => {
    return $api.lis.combined.save(model).then(() => {
      $notify.success("保存成功");
      editingObj.value = null;

      request("tableData", {
        pageSize: 20,
      });
    });
  },
  destroy: (ids: string) => {
    return $api.lis.combined.destroy(ids).then(() => {
      $notify.success("删除成功");

      request("tableData", {
        pageSize: 20,
      });
    });
  },
  listAsOptions: () => {
    return $api.lis.specimen.category.listAsOptions();
  },
  tubelistAsOptions: (params: any) => {
    return $api.lis.tube.listAsOptions(params);
  },
  loadcollectionMethod: () => $api.dict.item.listAsOptions("collection_method"),
  loadreportFormat: () => $api.dict.item.listAsOptions("report-format"),
  inspectionTeam: () => $api.dict.item.listAsOptions("inspection-team"),
  listinspectAsOptions: () => $api.lis.inspectGroup.listAsOptions(),
});

onMounted(() => {
  request("tableData");
  request("listAsOptions");
  request("tubelistAsOptions");
  request("loadcollectionMethod");
  request("loadreportFormat");
  request("inspectionTeam");
  request("listinspectAsOptions");
});

const pageParams = computed<DataPageProps>(() => {
  const queryFields: FormItemProps[] = [
    {
      prop: "name",
      label: "合管名称",
    },
  ];

  const headerActions: Action[] = [
    {
      label: "新增",
      event: "add",
      type: "primary",
    },
    {
      label: "批量对应采集方式",
      event: "collectionMethod",
      type: "primary",
      disabled: selectionRow?.value?.length == 0,
    },
  ];

  const dataPageProps: DataPageProps = {
    loading: loadingMap.tableData,
    queryModel: queryPramas,
    queryFields,
    actions: headerActions,
    onQuery: () => request("tableData"),
    onAct: onPageActions,
    columns: 2,
  };

  return dataPageProps;
});

const tableProps = computed(() => {
  const { tableData } = toRefs(data);

  const tableProps: TableProps = {
    loading: loadingMap.tableData,
    data: tableData.value?.items,
    pagination: tableData.value?.pagination,
    columns: [
      {
        type: "selection",
        label: "序号",
        width: "60px",
      },
      {
        prop: "name",
        label: "合管名称",
        tooltip: true,
      },
      {
        prop: "tubeId",
        label: "关联试管",
        tooltip: true,
        width: 120,
        render: ({ row }) => {
          const patientType = data.tubelistAsOptions ?? [];
          let resText = row.tubeId;
          let color = "";
          if (patientType && patientType.length > 0) {
            let filter = patientType.filter((item) => item.value == row.tubeId);
            if (filter && filter.length > 0) {
              resText = filter[0].label;
              color = filter[0]._raw.color;
            }
          }
          return h(
            "div",
            {
              style: {
                width: "100%",
                textAlign: "center",
              },
            },
            resText
          );
        },
      },
      {
        prop: "specimenTypeId",
        label: "关联标本",
        render: ({ row }) => {
          const patientType = data.listAsOptions ?? [];
          let resText = row.specimenTypeId;
          if (patientType && patientType.length > 0) {
            let filter = patientType.filter(
              (item) => item.value == row.specimenTypeId
            );
            if (filter && filter.length > 0) {
              resText = filter[0].label;
            }
          }
          return h("div", resText);
        },
      },
      {
        prop: "collectionMethod",
        label: "采集方式",
        render: ({ row }) => {
          const patientType = data.loadcollectionMethod ?? [];
          let resText = row.collectionMethod;
          if (patientType && patientType.length > 0) {
            let filter = patientType.filter(
              (item) => item.value == row.collectionMethod
            );
            if (filter && filter.length > 0) {
              resText = filter[0].label;
            }
          }
          return h("div", resText);
        },
      },

      {
        prop: "reportFormat",
        label: "检验周期",
        render: ({ row }) => {
          const patientType = data.loadreportFormat ?? [];
          let resText = row.reportFormat;
          if (patientType && patientType.length > 0) {
            let filter = patientType.filter(
              (item) => item.value == row.reportFormat
            );
            if (filter && filter.length > 0) {
              resText = filter[0].label;
            }
          }
          return h("div", resText);
        },
      },
      {
        prop: "inspectionTeam",
        label: "检验小组",
        render: ({ row }) => {
          const patientType = data.listinspectAsOptions ?? [];
          let resText = row.inspectionTeam;
          if (patientType && patientType.length > 0) {
            let filter = patientType.filter(
              (item) => item.value == row.inspectionTeam
            );
            if (filter && filter.length > 0) {
              resText = filter[0].label;
            }
          }
          return h("div", resText);
        },
      },
      {
        label: "操作",
        actions: ["edit", "destroy"],
      },
    ],
    onAct: onPageActions,
    onPaginate: (pagination: QueryPagination) =>
      request("tableData", pagination),
    cellStyle: ({ row, column }) => {
      if (column.property === "tubeId") {
        return {
          background: `${row.color}!important`,
        };
      }
    },
    onRowClick: (row: any) => {
      selectEquipment.value = row;
    },
    onSelectionChange: (selection: any) => {
      selectionRow.value = selection;
    },
    highlightCurrentRow: true,
  };
  return tableProps;
});

const editFormProps = computed<EditFormProps>(() => {
  const formItems: FormItemProps[] = [
    {
      prop: "name",
      label: "合管名称",
      required: false,
    },
    {
      prop: "tubeId",
      label: "关联试管",
      required: false,
      as: "select",
      options: {
        loadMethod: () => $api.lis.tube.listAsOptions(),
        onSelect: (row: any) => {
          Object.assign(editingObj.value, {
            specimenTypeId: row._raw.specimenTypeId,
            collectionMethod: row._raw.collectionMethod,
          });
        },
      },
    },
    {
      prop: "specimenTypeId",
      label: "关联标本",
      required: false,
      as: "select",
      disabled: true,
      options: {
        loadMethod: () => $api.lis.specimen.category.listAsOptions(),
      },
    },
    {
      prop: "collectionMethod",
      label: "采集方式",
      required: false,
      as: "select",
      options: {
        loadMethod: () => $api.dict.item.listAsOptions("collection_method"),
      },
    },

    {
      prop: "reportFormat",
      label: "检验周期",
      required: false,
    },
    {
      prop: "inspectionTeam",
      label: "检验小组",
      required: false,
      as: "select",
      options: {
        loadMethod: () => $api.lis.inspectGroup.listAsOptions(),
      },
    },
    {
      prop: "specimenNotice",
      label: "标本须知",
      required: false,
      as: "select",
      options: {
        loadMethod: () => $api.dict.item.listAsOptions("specimen_notice"),
      },
    },
  ];

  const editProps: EditFormProps = {
    model: editingObj.value,
    items: formItems,
    loading: loadingMap.save,
    columns: 1,
    size: "mini",
    onClose: () => {
      editingObj.value = null;
    },
    onCancel: () => {
      editingObj.value = null;
    },
    onValidate: (model) => {
      request("save", model);
    },
  };

  return editProps;
});

const onPageActions = (action: IAction, model?: any) => {
  switch (action.event) {
    case "add":
    case "edit":
      editingObj.value = $api.lis.combined.$$createEntity(model);
      break;
    case "destroy":
      request("destroy", model ? model.id : "");
      break;
    case "collectionMethod":
      collectionMethodShow.value = true;
      break;
  }
};

watch(
  () => editingObj?.value?.specimenTypeId,
  (item) => {
    if (item) {
    } else {
    }
  },
  {
    immediate: true,
  }
);
</script>

<style lang="less" scoped></style>
